package cn.sycoder.controller;

import cn.sycoder.entity.Menu;
import cn.sycoder.exception.BusinessException;
import cn.sycoder.mapper.MenuMapper;
import cn.sycoder.mapper.RoleMenuMapper;
import cn.sycoder.mapper.UserMapper;
import cn.sycoder.resp.Code;
import cn.sycoder.service.IMenuService;
import cn.sycoder.utils.JwtUtil;
import cn.sycoder.utils.MenusUtil;
import cn.sycoder.vo.MenuVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 杨润发
 * @since 2024-10-21
 */
@RestController
@RequestMapping("/api")
@Api(tags = "获取用户菜单")
@Transactional(rollbackFor = Exception.class)
public class MenuController {

    @Autowired
    IMenuService service;

    @Autowired
    MenuMapper mapper; // 菜单mapper

    @Autowired
    UserMapper userMapper; // 用户mapper

    @Autowired
    RoleMenuMapper roleMenuMapper; // 角色菜单权限mapper

    @GetMapping("/menu")
    @ApiOperation(value = "获取菜单方法")
    public Map<String, Object> menus(@RequestParam("token") String token) {

        // 获取当前登录的用户名
        String username = JwtUtil.extractUsername(token);
        System.out.println("当前登录用户：" + username);

        List<Menu> menus = null;
        try {
            // 通过用户名查询用户所属角色id
            Long roleId = userMapper.selectRoleId(username);
            // 查询该角色有哪些菜单的权限，并获取菜单id进行批量查询（即登录用户能够访问到所属角色权限的菜单）
            List<Long> menuIds = roleMenuMapper.selectMenuId(roleId);
            // 执行批量查询，获取菜单列表
            menus = mapper.selectBatchIds(menuIds);
        }catch (BusinessException e){
            new BusinessException(Code.BUSINESS_ERR,"业务处理异常，请稍后再试！");
        }

        // 先查询父级菜单，再查询父级菜单下的子菜单（遍历菜单列表）
        List<MenuVo> parentMenus = new ArrayList<>(); // 父级菜单
        List<MenuVo> sonMenus = new ArrayList<>(); // 子菜单
        for (Menu menu : menus) {
            MenuVo menuVo = new MenuVo();
            BeanUtils.copyProperties(menu, menuVo); // 包装新MenuVo
            if (menu.getPid() == null) { // 如果菜单pid为空（表示该菜单为父级菜单）
                parentMenus.add(menuVo); // 添加到父级菜单中
            }
            sonMenus.add(menuVo); // 菜单pid不为空，表示该菜单为子菜单
        }

        // 排序
        List<MenuVo> parentOrderMenus = parentMenus.stream()
                .sorted(Comparator.comparing(MenuVo::getOrderValue))
                .collect(Collectors.toList());

        for (MenuVo orderMenu : parentOrderMenus) {
            List<MenuVo> child = MenusUtil.getChild(orderMenu.getId(), sonMenus);
            List<MenuVo> collect = child.stream()
                    .sorted(Comparator.comparing(MenuVo::getOrderValue))
                    .collect(Collectors.toList());
            orderMenu.setMenus(collect);
        }

        // 创建响应结果
        HashMap<String, Object> response = new HashMap<>();

        if (parentOrderMenus != null) {
            response.put("success", true);
            response.put("data", parentOrderMenus);
        } else {
            response.put("msg", "服务器异常！");
        }
        return response;
    }
}
